package com.qf.android.sport.fragment.news;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.qf.android.sport.R;
import com.qf.android.sport.activity.InterestActivity;
import com.qf.android.sport.adapter.PagerAdapter;
import com.qf.android.sport.callback.HttpService;
import com.qf.android.sport.entity.Channels;
import com.qf.android.sport.entity.TitleTotal;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsFragment extends Fragment implements Callback<TitleTotal>, View.OnClickListener {
 private List<Channels> list;
    private TabLayout tab;
    private ViewPager pager;

    public NewsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
           return inflater.inflate(R.layout.fragment_news, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        list = new ArrayList<>();
        pager = (ViewPager) view.findViewById(R.id.newpager);

        HttpService service = new Retrofit.Builder()
                .baseUrl("http://www.baidu.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(HttpService.class);
        service.getDatas().enqueue(this);
        tab = (TabLayout) view.findViewById(R.id.new_tab);


        ImageView imageView = (ImageView) view.findViewById(R.id.image_new);
        imageView.setOnClickListener(this);

    }

    @Override
    public void onResponse(Call<TitleTotal> call, Response<TitleTotal> response) {
        TitleTotal body = response.body();
        list = body.getData().getChannels();
        PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), list);
        pager.setAdapter(adapter);

        tab.setupWithViewPager(pager);
    }

    @Override
    public void onFailure(Call<TitleTotal> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    //跳转兴趣栏
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(pager.getContext(), InterestActivity.class);
        startActivity(intent);
    }
}
